package com.hmdp.utils;


import cn.hutool.core.lang.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/*
*  误删问题
*  1. 原子性导致的误删
*  2. 分布式导致的误删（可以使用lua脚本）
*
* */
public class simpleRedisLock implements ILock{


    private StringRedisTemplate stringRedisTemplate;

    private String name;
    private static final String KEY_PREFIX="lock:";
    private static final String ID_PREFIX= UUID.randomUUID().toString(true) +"-";

    public simpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }
    @Override
    public boolean tryLock(long timeoutSec) {
//        get process name
        String threadID=ID_PREFIX+Thread.currentThread().getId();
        long id = Thread.currentThread().getId();
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadID, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(b);
    }

    @Override
    public void unlock() {
        String threadID=ID_PREFIX+Thread.currentThread().getId();
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);

        if(threadID.equals(id)){
            stringRedisTemplate.delete(KEY_PREFIX+name);
        }

//        释放锁

    }
}
